package tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class ServerDemo {
    public static void main(String[] args) throws IOException {
        //创建ServerSocket服务器对象
        ServerSocket serverSocket = new ServerSocket(10086);
            //通过ServerSocket服务器对象调用accept方法来获取socket对象
            Socket socket = serverSocket.accept();
            //通过socket对象来调用getInputStream()方法来读取客户端传来的数据
            InputStream is = socket.getInputStream();
            //将InputStream封装为InputStreamReader，防止客户端传来的数据中有中文
            InputStreamReader isr = new InputStreamReader(is);
            char[] ch= new char[1024];
            int len;
            //read方法具有阻塞作用
            while((len=isr.read(ch))!=-1) {
                System.out.println(new String(ch,0,len));
            }

            //给客户端反馈数据
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            Scanner sc = new Scanner(System.in);
            String details = sc.next();
            bw.write(details);
            //写入换行符
            bw.newLine();
            bw.flush();
            socket.shutdownOutput();
            //释放资源可以省略
        }
}
